package zj.com.activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import zj.com.adapter.TjAdapter;
import zj.com.adapter.TjExpandableListViewAdapter;
import zj.com.app.ZjApplication;
import zj.com.model.DjcModel;
import zj.com.model.GsTj;
import zj.com.model.GsTjOrg;
import zj.com.model.JcxDB;
import zj.com.model.Org;
import zj.com.model.Project;
import zj.com.model.User;
import zj.com.net.NetManager;
import zj.com.net.OnResponseListener;
import zj.com.util.DateTimePickDialogUtil;
import zj.com.util.DateUtil;
import zj.com.util.DialogUtil;
import zj.com.util.LogUtils;
import zj.com.util.SharedPreferencesUtil;
import zj.com.zj.R;

/**
 * Created by xi on 16/6/12.
 *
 * 公司统计
 */
public class GstjActivity extends  BaseActivity implements View.OnClickListener{


    public TextView title_name,right_tv,one_tv,two_tv,three_tv,four_tv;
    public ImageView left_iv;
    public List<GsTj> list;
    public TjExpandableListViewAdapter adapter;
    public Intent intent;
    public ImageView id_tab_line_iv;
    public int screenWidth;


    public RelativeLayout gs_rl;
    public TextView gs_tv,bm_tv,jcr_tv,start_tv,end_tv;
    public Button queryBtn,resetBtn;
    public LinearLayout total_ll;
    private String initStartDateTime = "2013年9月3日 14:44"; // 初始化开始时间
    public ExpandableListView expListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gstj);

        initView();
        initTabLineWidth();
        initData();
    }
    public String endTime;
    public String startTime;
    public void initView(){


        resetBtn = (Button) findViewById(R.id.resetBtn);
        resetBtn.setOnClickListener(this);
        gs_tv = (TextView) findViewById(R.id.gs_tv);
        bm_tv = (TextView) findViewById(R.id.bm_tv);
        bm_tv.setOnClickListener(this);
        jcr_tv = (TextView) findViewById(R.id.jcr_tv);
        jcr_tv.setOnClickListener(this);
        start_tv = (TextView) findViewById(R.id.start_tv);
        start_tv.setOnClickListener(this);
        end_tv = (TextView) findViewById(R.id.end_tv);
        end_tv.setOnClickListener(this);

        start_tv = (TextView) findViewById(R.id.start_tv);
        start_tv.setOnClickListener(this);
        end_tv = (TextView) findViewById(R.id.end_tv);
        end_tv.setOnClickListener(this);
        Calendar calendar2 = Calendar.getInstance();
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        String dateTime2 = sdf2.format(calendar2.getTime());
        endTime = dateTime2;
        end_tv.setText(DateUtil.formatStrimgDate3(endTime));


        Calendar calendar3 = Calendar.getInstance();
        Date theDate=calendar3.getTime();
        GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
        gcLast.setTime(theDate);
        //设置为第一天
        gcLast.add(Calendar.MONTH, -3);
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        String dateTime3 = sdf3.format(gcLast.getTime());
        startTime = dateTime3;
        start_tv.setText(DateUtil.formatStrimgDate3(startTime));

        gs_rl = (RelativeLayout) findViewById(R.id.gs_rl);
        gs_rl.setOnClickListener(this);
        queryBtn = (Button) findViewById(R.id.queryBtn);
        queryBtn.setOnClickListener(this);
        total_ll = (LinearLayout) findViewById(R.id.total_ll);
        total_ll.setVisibility(View.GONE);
        id_tab_line_iv = (ImageView) findViewById(R.id.id_tab_line_iv);

        one_tv = (TextView) findViewById(R.id.one_tv);
        one_tv.setOnClickListener(this);
        two_tv = (TextView) findViewById(R.id.two_tv);
        two_tv.setOnClickListener(this);

        three_tv = (TextView) findViewById(R.id.three_tv);
        three_tv.setOnClickListener(this);

        four_tv = (TextView) findViewById(R.id.four_tv);
        four_tv.setOnClickListener(this);

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        String dateTime = sdf.format(calendar.getTime());
        initStartDateTime = dateTime;

        title_name = (TextView) findViewById(R.id.title_name);
        title_name.setText("公司统计");
        right_tv = (TextView) findViewById(R.id.right_tv);
        right_tv.setText("报表模式");
        right_tv.setVisibility(View.VISIBLE);
        left_iv = (ImageView) findViewById(R.id.left_iv);
        left_iv.setOnClickListener(this);
        left_iv.setVisibility(View.VISIBLE);

        expListView = (ExpandableListView) findViewById(R.id.asset_grid);
        right_tv.setVisibility(View.GONE);
        right_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(GstjActivity.this,BarChartActivityMultiDataset.class);
                intent.putExtra("type",0);
                startActivity(intent);
            }
        });

    }

    private void initTabLineWidth() {
        DisplayMetrics dpMetrics = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay()
                .getMetrics(dpMetrics);
        screenWidth = dpMetrics.widthPixels;
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) id_tab_line_iv
                .getLayoutParams();
        lp.width = screenWidth / 4;
        id_tab_line_iv.setLayoutParams(lp);
    }

    public void initData(){
        list = new ArrayList<GsTj>();


        adapter = new TjExpandableListViewAdapter(this,list);
        expListView.setAdapter(adapter);
//        expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
//
//            @Override
//            public boolean onGroupClick(ExpandableListView parent, View v,
//                                        int groupPosition, long id) {
//                // TODO Auto-generated method stub
//                return true;
//            }
//        });

    }


    public final int GS_CODE = 0x2210;
    public final int BM_CODE = GS_CODE+1;
    public final int JCR_CODE = GS_CODE+2;

    public ProgressDialog dialog;

    @Override
    public void onClick(View v) {

        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) id_tab_line_iv
                .getLayoutParams();
        switch(v.getId()){
            case R.id.left_iv:
                finish();
                break;
            case R.id.one_tv:
                type = 0;
                lp.leftMargin =0;
                one_tv.setTextColor(Color.parseColor("#6799ff"));
                two_tv.setTextColor(Color.parseColor("#a4a4a4"));
                three_tv.setTextColor(Color.parseColor("#a4a4a4"));
                four_tv.setTextColor(Color.parseColor("#a4a4a4"));

                break;
            case R.id.two_tv:
                type = 1;
                lp.leftMargin =
                        screenWidth / 4;
                one_tv.setTextColor(Color.parseColor("#a4a4a4"));
                two_tv.setTextColor(Color.parseColor("#6799ff"));
                three_tv.setTextColor(Color.parseColor("#a4a4a4"));
                four_tv.setTextColor(Color.parseColor("#a4a4a4"));
                break;
            case R.id.three_tv:
                type = 2;
                lp.leftMargin =
                        screenWidth / 2;
                one_tv.setTextColor(Color.parseColor("#a4a4a4"));
                two_tv.setTextColor(Color.parseColor("#a4a4a4"));
                three_tv.setTextColor(Color.parseColor("#6799ff"));
                four_tv.setTextColor(Color.parseColor("#a4a4a4"));
                break;
            case R.id.four_tv:
                type = 3;
                lp.leftMargin =
                        screenWidth*3 / 4;
                one_tv.setTextColor(Color.parseColor("#a4a4a4"));
                two_tv.setTextColor(Color.parseColor("#a4a4a4"));
                three_tv.setTextColor(Color.parseColor("#a4a4a4"));
                four_tv.setTextColor(Color.parseColor("#6799ff"));
                break;
            case R.id.queryBtn:
                query();
                break;
            case R.id.start_tv:

                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                        GstjActivity.this, startTime,false);
                DateTimePickDialogUtil.isVisibleTime = false;
                dateTimePicKDialog.dateTimePicKDialog(start_tv);
                break;
            case R.id.end_tv:
                DateTimePickDialogUtil.isVisibleTime = false;
                DateTimePickDialogUtil dateTimePicKDialog2 = new DateTimePickDialogUtil(
                        GstjActivity.this, endTime,false);
                dateTimePicKDialog2.dateTimePicKDialog(end_tv);
                break;
            case R.id.gs_rl:

                intent = new Intent(GstjActivity.this,GsSelectActivity.class);
                intent.putExtra("isMutiSelect",true);
                intent.putExtra("type",0);
                startActivityForResult(intent, GS_CODE);
                break;
            case R.id.bm_tv:
                intent = new Intent(GstjActivity.this,GsSelectActivity.class);
                intent.putExtra("type",1);
                if(gsList != null && gsList.size() > 0){
                    intent.putExtra("org",gsList.get(0));
                }
               //
                startActivityForResult(intent,BM_CODE);
                break;
            case R.id.jcr_tv:
                intent = new Intent(GstjActivity.this,JcrSelectDoubleListActivity.class);
                startActivityForResult(intent, JCR_CODE);
                break;
            case R.id.resetBtn:
                user = null;
                this.gsList = null;
                jcr_tv.setText("检查人");
                gs_tv.setText("公司选择");
                end_tv.setText("结束日期");
                start_tv.setText("开始日期");
                break;

        }
        id_tab_line_iv.setLayoutParams(lp);

    }

    public Org bm;
    public User user;
    public List<Org> gsList;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == RESULT_OK){

            switch(requestCode){
                case BM_CODE:
                    bm = (Org) data.getSerializableExtra("org");
                    bm_tv.setText(bm.getOrgName());
                    this.bm = bm;
                    break;
                case GS_CODE:

                    List<Org>  orgs= (List<Org>) data.getSerializableExtra("org");
                    if(orgs != null && orgs.size() > 0){
                        StringBuffer sb = new StringBuffer();
                        for(Org org:orgs){
                            sb.append(org.getOrgName()+",");

                        }
                        gs_tv.setText(sb.toString());

                    }
                    this.gsList = orgs;
                    break;
                case JCR_CODE:
                    user = (User) data.getSerializableExtra("user");
                    this.user = user;
                    jcr_tv.setText(user.getUserName());
                    break;

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public int type = 0;
    public List<GsTj> gstjList;
    public Map<String,List<GsTjOrg>> map;
    public void query(){

        try {
        String request = "";

            JSONObject obj = new JSONObject();
            String uid = (String) SharedPreferencesUtil.getData(this, "uid", "");
            JSONArray array = new JSONArray();


            String startTime = start_tv.getText().toString();
            String endTime = end_tv.getText().toString();
            if(gsList == null || gsList.size() == 0){

                Toast.makeText(GstjActivity.this, "请选择你要查询的公司", Toast.LENGTH_SHORT).show();
                return;
            }


//            if(user == null){
//                Toast.makeText(GstjActivity.this, "请选择检查人", Toast.LENGTH_SHORT).show();
//                return;
//
//            }

            if(TextUtils.isEmpty(startTime) || startTime.equals("开始日期"))
            {
                Toast.makeText(GstjActivity.this, "请选择你开始时间", Toast.LENGTH_SHORT).show();
                return;
            }
            if(TextUtils.isEmpty(endTime) || endTime.equals("结束日期"))
            {
                Toast.makeText(GstjActivity.this, "请选择你结束时间", Toast.LENGTH_SHORT).show();
                return;
            }


            int date = DateUtil.compare_date(startTime,endTime);

            LogUtils.getInstance().error("   date === "+date);
            if(date > 0 ){
                Toast.makeText(GstjActivity.this, "开始日期不能大于结束日期", Toast.LENGTH_SHORT).show();
                return ;
            }


            for(Org org :gsList){
                array.put(org.getOrgCode());
            }
            if(user != null){
                obj.put("InspectUserID", user.getUserID());
            }
            obj.put("OrgCodeList",array);
            obj.put("InspectOrgCode","");
            obj.put("InspectBeginDate",startTime);
            obj.put("InspectEndDate",endTime);
            obj.put("Level","0");
            obj.put("Type",type+"");//RiskType=0 Inspectype=1  RiskLevel=2  InspectTimes=3


            LogUtils.getInstance().error("====query====="+obj.toString());

            dialog = DialogUtil.createProgressDialog(this,"提示","数据查询中..");

        NetManager.getInstance(this).GetAnalysisForCompanyByInspectype(type, obj.toString(), new OnResponseListener<List<GsTj>>() {
            @Override
            public void onComplete(boolean isOK, List<GsTj> result, int errorCode, String errorMsg) {


                if (isOK) {

                    if (result == null || result.size() == 0) {
                        Toast.makeText(GstjActivity.this, "数据为空", Toast.LENGTH_SHORT).show();
                        return;

                    }
                    ZjApplication.gstjList = result;
                    right_tv.setVisibility(View.VISIBLE);

                    adapter.setDataChanage(result);
                    expListView.expandGroup(0);

                } else {
                    Toast.makeText(GstjActivity.this, "获取失败", Toast.LENGTH_SHORT).show();

                }

                dialog.dismiss();

            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {

                Toast.makeText(GstjActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
                dialog.dismiss();

            }
        });

        }catch(Exception e){
            LogUtils.getInstance().error(e.toString());
            Toast.makeText(GstjActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
            if(dialog != null)
            dialog.dismiss();

        }
    }


}
